package com.um2.mauction.session.impl;

import java.util.List;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.um2.mauction.entity.Enchere;
import com.um2.mauction.entity.Utilisateur;
import com.um2.mauction.entity.Vente;
import com.um2.mauction.session.remote.EnchereManagerRemote;

@Remote(EnchereManagerRemote.class)
@Stateless
public class EnchereManagerBean implements EnchereManagerRemote
{
	public static String RemoteJNDIName = EnchereManagerBean.class.getSimpleName() + "/remote";
	
	@PersistenceContext
	private EntityManager em;	
    
	/**
	 * Retourne l'enchere a partir de son identifiant
	 */
	public Enchere getEnchere(int idBid) 
	{
		return em.find(Enchere.class,idBid);		
	}
	
	/**
	 * Ajoute une enchere
	 */
		
	public void addEnchere(float amount,Utilisateur bidder,Vente sale)
	{
		Enchere bid = new Enchere(amount,bidder,sale);
		em.persist(bid);	
		bidder.getBids().add(bid);
		sale.getBids().add(bid);	
		//em.flush();
	}
	
	public void addEnchere(Enchere e)
	{
		em.persist(e);	
		//e.getBidder().getBids().add(e);
		//e.getSale().getBids().add(e);
		//bidder.getBids().add(e);
		//sale.getBids().add(e);
	}
	
	/**
	 * Met a jour une enchere
	 */
	public void updateEnchere(int idBid,float amount,Utilisateur bidder,Vente sale) 
	{
		Enchere e = em.find(Enchere.class,idBid);
		e.setAmount(amount);
		e.setBidder(bidder);
		e.setSale(sale);
	}
	
	/**
	 * Supprime une enchere
	 */
	public void deleteEnchere(int idBid) 
	{
		Enchere e = em.find(Enchere.class,idBid);
		em.remove(e);
	}

	/**
	 * Retourne la liste de toutes les encheres
	 */
	@SuppressWarnings("unchecked")
	public List<Enchere> getAllEncheres() 
	{
		Query query = em.createQuery( "SELECT e " +
									  "FROM Enchere e ");
		// Get encheres
		List<Enchere> encheres = query.getResultList();		
		return encheres;
	}
	
	public Enchere getLastBid(){
		return null;
	}
}